import DailyApi from '../../../../common/api/bi/pigsltrdailyinfo.api.js';
import doT from '../../../../../vendor/template/doT.js';
import watermark from '../../../../common/watermark.js';
import { DictionaryType, requestDict } from '../../../../common/dictionary/dictionary-type.js';

Utils.NameSpace('SN.CptvPlf.PigSlaughter');
(function (window, document, $) {
    let _vm,
        pieEcartsData,
        lineEcartsData,
        _sitesInfo = {};
    $(async function () {
        // JS严格模式
        'use strict';
        await requestDict(DictionaryType.SLTRSITE_TYPE).then((result) => {
            if (result.isSucceed) {
                result.data.forEach((item) => {
                    _sitesInfo[item.value] = item.displayName;
                });
            }
        });
        watermarkBgImg();
        _vm = new Vue({
            el: '#divPage',
            data() {
                return {
                    readingUser: [],
                };
            },
            async created() {
                let bizDate = getUrlKey('id');
                let that = this;
                let thisYear = new Date(bizDate).getFullYear();
                let resData = { bizDate: [], sumAvgPrice: [] };
                DailyApi.postDailyList({ startDate: bizDate, endDate: bizDate }).then(async (res) => {
                    if (Utils.IsNotNull(res)) {
                        // 总的数据
                        let yeartotal = {
                            curMSelfQty: 0,
                            curMAgentQty: 0,
                            curYQty: 0,
                            curYSelfQty: 0,
                            curYAgentQty: 0,
                        };
                        res.map((item) => {
                            // 本月自营屠宰量
                            yeartotal.curMSelfQty += item.curMSelfQty;
                            // 本月代宰屠宰量
                            yeartotal.curMAgentQty += item.curMAgentQty;
                            // 本年累计屠宰量
                            yeartotal.curYQty += item.curYQty;
                            // 本年自营屠宰量
                            yeartotal.curYSelfQty += item.curYSelfQty;
                            // 本年代宰屠宰量
                            yeartotal.curYAgentQty += item.curYAgentQty;
                        });
                        yeartotal.year = thisYear;
                        let _template = doT.template($('#dailyList_template').text());
                        let annualInfo_template = doT.template($('#annualInfo_template').text());
                        $('#annualInfo').append(annualInfo_template(yeartotal));
                        lineEcarts(yeartotal);

                        // 各个公司的数据
                        await res.map((item) => {
                            item['bizDate'] = moment(item.bizDate).format('YYYY-MM-DD');
                            item['oName'] = item.name;
                            item.details.forEach((det) => {
                                det['sourceName'] = _sitesInfo[det.source];
                            });
                            $('#dailyList').append(_template(item));
                        });
                        // 总均价 7天内的数据
                        let time = new Date(bizDate).getTime() - 6 * 24 * 60 * 60 * 1000;
                        let tragetTime = new Date(time);
                        let bizDateBefore =
                            tragetTime.getFullYear() + '-' + (tragetTime.getMonth() + 1 > 9 ? tragetTime.getMonth() + 1 : '0' + (tragetTime.getMonth() + 1)) + '-' + (tragetTime.getDate() > 9 ? tragetTime.getDate() : '0' + tragetTime.getDate());

                        await DailyApi.postDailyweaList({ startDate: bizDateBefore, endDate: bizDate }).then((resWea) => {
                            if (Utils.IsNotNull(resWea)) {
                                // 按 bizDate 排序
                                resWea.sort((a, b) => new Date(a.bizDate) - new Date(b.bizDate));
                                resWea.forEach((item) => {
                                    let dataArr = moment(item.bizDate).format('YYYY-MM-DD').split(/[-: ]/);
                                    resData.bizDate.push(`${dataArr[1]}-${dataArr[2]}`);
                                    resData.sumAvgPrice.push(Utils.toThousands(item.sumAvgPrice));
                                });
                            }
                        });
                        pieEcartsData = resData;
                        lineEcartsData = res.total;
                        pieEcarts(resData);
                    } else {
                        let total = { year: thisYear, curYQty: 0, curYSelfQty: 0, curYAgentQty: 0 };
                        let entries = {
                            oName: '云南神农肉业食品有限公司',
                            bizDate: thisYear,
                            daily: {
                                sumAvgWeight: 0,
                                sumQty: 0,
                                sumAvgPrice: 0,
                                selfQty: 0,
                                selfAvgWeight: 0,
                                selfAvgPrice: 0,
                                agentQty: 0,
                                outQty: 0,
                                agentSltrAvgWeight: 0,
                                agentAvgPrice: 0,
                                spzQJQty: 0,
                                spzYZQty: 0,
                                spzDSQty: 0,
                            },
                        };
                        let _template = doT.template($('#dailyList_template').text());
                        let annualInfo_template = doT.template($('#annualInfo_template').text());
                        $('#dailyList').append(_template(entries));
                        $('#annualInfo').append(annualInfo_template(total));
                    }
                });
            },
        });
        swiperInit();
    });
    const getUrlKey = (name) => {
        /** 获取地址栏的 参数  传入 字段返回值 */
        var reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)', 'i');
        var r = window.location.search.substr(1).match(reg);
        if (r != null) return unescape(r[2]);
        return null;
    };
    const swiperInit = () => {
        let mySwiper = new Swiper('.swiper-container', {
            speed: 1000, //播放速度
            // autoHeight: true,
            loop: false, //循环 最后面一个往后面滑动会滑到第一个
            setWrapperSize: true,
            pagination: {
                //分页器
                el: '.swiper-pagination',
                clickable: true,
            },
            effect: 'slide', //动画效果
            on: {
                slideChangeTransitionStart: function () {
                    switch (this.activeIndex) {
                        case 1:
                            pieEcarts(pieEcartsData);
                            break;
                        case 2:
                            lineEcarts(lineEcartsData);
                            break;
                    }
                },
            },
        });
    };
    function pieEcarts(res) {
        let isRotate = document.body.scrollWidth <= 350 ? '-20' : 0;
        var chartDom = document.getElementById('lineAvg');
        var myChart = echarts.init(chartDom);
        var option;
        option = {
            legend: {
                data: ['总均价'],
                x: 'center',
                top: '5%',
            },
            tooltip: {
                trigger: 'axis',
                formatter: function (data) {
                    return `${data[0].axisValue}<br/>${data[0].marker}${data[0].seriesName}&emsp;&emsp;${data[0].value} 元/kg`; //将小数转化为百分数显示
                },
            },
            grid: {
                right: '7%',
                left: '15%',
            },
            xAxis: {
                type: 'category',
                data: res.bizDate,
                axisLabel: {
                    // X轴title倾斜
                    interval: 0, //坐标轴刻度标签的显示间隔(在类目轴中有效) 0:显示所有  1：隔一个显示一个 :3：隔三个显示一个...
                    rotate: isRotate, //标签倾斜的角度，显示不全时可以通过旋转防止标签重叠（-90到90）
                },
            },
            yAxis: {
                type: 'value',
                scale: true,
                axisLabel: {
                    formatter: function (value, index) {
                        return value.toFixed(2);
                    },
                },
            },
            series: [
                {
                    name: '总均价',
                    data: res.sumAvgPrice,
                    type: 'line',
                    smooth: true,
                    lineStyle: {
                        color: '#73c0de',
                    },
                    itemStyle: {
                        normal: {
                            color: '#73c0de',
                        },
                    },
                },
            ],
        };

        option && myChart.setOption(option);
    }
    function lineEcarts(res) {
        var chartDom = document.getElementById('pieTotalNumber');
        var myChart = echarts.init(chartDom);
        var option;
        option = {
            title: {
                text: '屠宰加工月屠宰量',
                left: 'center',
                y: 'bottom',
                top: '75%',
            },
            tooltip: {
                trigger: 'item',
                formatter: '{b} : {c} 头 ({d}%)',
            },
            grid: {
                y: 100,
            },
            series: [
                {
                    type: 'pie',
                    radius: 80,
                    center: ['50%', '37%'],
                    itemStyle: {
                        borderRadius: 5,
                    },
                    startAngle: 135, //起始角度
                    label: {
                        normal: {
                            show: true,
                            formatter: '{b}: {c} 头\n({d}%)',
                        },
                    },
                    labelLine: {
                        length: 10, //长度
                        length2: 5, //宽度
                    },
                    data: [
                        {
                            value: res.curMSelfQty,
                            name: '自营',
                            itemStyle: {
                                normal: {
                                    color: '#3e8ef7',
                                },
                            },
                        },
                        {
                            value: res.curMAgentQty,
                            name: '代宰',
                            itemStyle: {
                                normal: {
                                    color: '#73c0de',
                                },
                            },
                        },
                    ],
                },
            ],
            emphasis: {
                itemStyle: {
                    shadowBlur: 10,
                    shadowOffsetX: 0,
                    shadowColor: 'rgba(0, 0, 0, 0.5)',
                },
            },
        };

        option && myChart.setOption(option);
    }
    const watermarkBgImg = () => {
        let _userInfo = JSON.parse(Utils.GetSessionStorage('SNAccountEply')) || JSON.parse(Utils.GetSessionStorage('SNLoginUserInfo'));
        return DailyApi.queryUserInfo()
            .then((res) => {
                watermark.set(res.name + res.numCode); // 水印
            })
            .catch((_) => {
                watermark.set(_userInfo.un); // 水印
            });
        // let _userInfo = JSON.parse(Utils.GetSessionStorage("SNLoginUserInfo")) || {};
        // DailyApi.queryUserName(Utils.GetQueryString('state') || '').then(res => {
        //     watermark.set(_userInfo.curUserName + res.code);// 水印
        // }).catch(_ => {
        //     watermark.set(_userInfo.curUserName);// 水印
        // });
    };
})(window, document, jQuery);
